package com.ballyza;

import java.io.StringReader;

import com.ballyza.gals.LexicalError;
import com.ballyza.gals.Lexico;
import com.ballyza.gals.Token;
import com.ballyza.gals.TokenNames;

public class BallyzaLexical {

	private final static String INVALID_SYMBOL = "símbolo inválido";
	
	private final CompileResult result;
	
	private final String text;
	private Lexico anallyzer;
	private Token token;

	public BallyzaLexical(String text, CompileResult result) {
		this.text = text;
		this.result = result;
	}
	
	public Lexico getLexico() {
		return new Lexico(new StringReader(text));
	}
	
	public void start() {
		String[] lines = text.split("\n");
		
		int count = 0;
		
		result.setSuccess(true);
		for(String line : lines) {
			anallyzer = new Lexico(new StringReader(line.concat(newLine())));
			
			do {
				try {
					token = anallyzer.nextToken();
					
					if(token != null) {
						LexicalResult lexicalResult = new LexicalResult(token.getLexeme(), TokenNames.get(token.getId()), count+1);
						result.addLexicalResult(lexicalResult);
					}
					
				} catch(LexicalError error) {
					result.setSuccess(false);
					String errorMessage = "Erro na linha ".concat(String.valueOf(count+1)).concat(" - ");
					if(error.getMessage().equalsIgnoreCase("Caractere não esperado")) 
						errorMessage = errorMessage.concat(String.valueOf(error.getCharacter())).concat(" ").concat(INVALID_SYMBOL);
					else
						errorMessage = errorMessage.concat(" ").concat(error.getMessage());
				
					this.result.setErrorMessage(errorMessage);
					
					result.setSuccess(false);
				}
			} while(token != null);
			
			count++;
		}
		
	}
	
	private String newLine() {
		return "\n";
	}
	
	public String getText() {
		return text;
	}
	
}